package com.panopset.game.blackjack;

import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;

/**
 * Blackjack card counting system.
 * @author Karl Dinwiddie
 *
 */
public class CountingSystem implements Comparable<CountingSystem> {

    private int counter;
    private final Integer sel;
    private final String nm;
    private final Map<String, Integer> vals = new HashMap<String, Integer>();

    public CountingSystem(final String name, final String dta, final int selection) {
        sel = selection;
        nm = name;
        StringTokenizer st = new StringTokenizer(dta, " ");
        try {
            vals.put("2", parse(st.nextToken().trim()));
            vals.put("3", parse(st.nextToken().trim()));
            vals.put("4", parse(st.nextToken().trim()));
            vals.put("5", parse(st.nextToken().trim()));
            vals.put("6", parse(st.nextToken().trim()));
            vals.put("7", parse(st.nextToken().trim()));
            vals.put("8", parse(st.nextToken().trim()));
            vals.put("9", parse(st.nextToken().trim()));
            vals.put("T", parse(st.nextToken().trim()));
            vals.put("A", parse(st.nextToken().trim()));
        } catch(Throwable t) {
            throw new RuntimeException(dta, t);
        }
    }

    /**
     * Pre-Java 7, you have to take out the + sign.
     * @return
     */
    public int parse(final String s) {
        if (s.charAt(0) == '+') {
            return Integer.parseInt(s.substring(1));
        } else {
            return Integer.parseInt(s);
        }
    }
    public String getName() {
        return nm;
    }

    public int getCount() {
        return counter;
    }

    public void count(BlackjackCard blackjackCard) {
        if (blackjackCard.isAce()) {
            counter = counter + vals.get("A");
        } else {
            String valRep = "" + blackjackCard.getSoftValue();
            if ("10".equals(valRep)) {
                valRep = "T";
            }
            counter = counter + vals.get(valRep);
        }
    }

    public int getSelection() {
        return sel;
    }
    @Override
    public int compareTo(final CountingSystem o) {
        return sel.compareTo(o.sel);
    }

    public void reset() {
        counter = 0;
    }
}
